package com.hyl.dao;

import com.hyl.entity.Person;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/12/26 8:48
 **/
public class PersonDaoImpl extends BaseDao implements PersonDao {
	@Override
	public List<Person> findAll() {
		List<Person> list = new ArrayList<>();
		//1、连接Connection
		Connection conn = getConnection();
		//2、编写sql
		String sql = "Select * from person order by id desc";
		//3、创建执行对象
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			//4、执行
			rs =  pstm.executeQuery();
			//5、处理
			while(rs.next()){
				Person tmp = new Person( rs.getInt("id"),
						rs.getString("name"),
						rs.getString("sex"),
						rs.getInt("age"),
						rs.getString("rank"),
						rs.getString("department"));
				list.add(tmp);
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//6、关闭
			closeAll(conn, pstm, rs);
		}

		return list;
	}

	@Override
	public int add(Person person) {
		//1、连接Connection
		Connection conn = getConnection();
		//2、编写sql
		String sql = "insert into person( name,  sex,  age,  rank,  department) values(?,  ?,  ?,  ?,  ?)";
		//3、创建执行对象
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, person.getName());
			pstm.setString(2, person.getSex());
			pstm.setInt(3, person.getAge());
			pstm.setString(4, person.getRank());
			pstm.setString(5, person.getDepartment());
			//4、执行
			return pstm.executeUpdate();
			//5、处理
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//6、关闭
			closeAll(conn, pstm, rs);
		}
		return 0;
	}

	@Override
	public int del(Integer id) {
		//1、连接Connection
		Connection conn = getConnection();
		//2、编写sql
		String sql = "delete  from person where id=?";
		//3、创建执行对象
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setInt(1, id);
			//4、执行
			return pstm.executeUpdate();
			//5、处理
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//6、关闭
			closeAll(conn, pstm, rs);
		}
		return 0;
	}

	@Override
	public int checkName(String name) {
		//1、连接Connection
		Connection conn = getConnection();
		//2、编写sql
		String sql = "Select count(1) as cnt from person where name=?";
		//3、创建执行对象
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, name);
			//4、执行
			rs =  pstm.executeQuery();
			//5、处理
			int ret = 0;
			while(rs.next()){
				ret = rs.getInt("cnt");
			}
			return ret ;
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}finally {
			//6、关闭
			closeAll(conn, pstm, rs);
		}

		return 0;
	}
}
